//
//  MaterialViewController.m
//  OrderAssistant
//
//  Created by chendong on 2020/8/26.
//  Copyright © 2020 chendong. All rights reserved.
//

#import "MaterialViewController.h"
#import "RightMaterialTableViewCell.h"
#import "LeftMaterialTableViewCell.h"
#import "CargoBoxViewController.h"
#import "TheMaterialSearchViewController.h"
#import "NetTools.h"
#import <SVProgressHUD.h>
#import <AFNetworking.h>
#import "FCUUID.h"
@interface MaterialViewController ()<UITableViewDelegate,UITableViewDataSource,UITextFieldDelegate,UIAlertViewDelegate>
@property (nonatomic,strong) UITableView *myTableView;
@property (nonatomic,strong) UITableView *rightTableView;
@property (nonatomic,strong) UIButton *wlssBtn;//物料搜索
@property (nonatomic,strong) UIView *bottomBGV;//查看货框
@property (nonatomic,strong) NSMutableArray *dataMarr;//物料数据
@property (nonatomic,strong) NSDictionary *dataDic;//物料数据
@property (nonatomic,strong) UIView *mbV;
@property (nonatomic,strong) UIView *srBgV;
@property (nonatomic,strong) UITextField *srBgVTF;
@property (nonatomic,strong) UILabel *wlL;
@property (nonatomic,strong) LeftMaterialTableViewCell *wlLCell;
@property (nonatomic,strong) RightMaterialTableViewCell *rightWlLCell;
@property (nonatomic,strong) NSIndexPath *rightWlLCellIndexPath;
@property (nonatomic,strong) UILabel *nxljzwlL;
@property (nonatomic,strong) UILabel *wljbL;
@property (nonatomic,strong) NSIndexPath *wlLCellIndexPath;
@property (nonatomic,assign) BOOL didscroll;
@property (nonatomic,assign) BOOL isTffff;
@property (nonatomic,strong) UIAlertView *alerV;
@property (nonatomic,strong) UIButton *lsddBtn;
@property (nonatomic,strong) UIButton *hkBtn;
@property (nonatomic,strong) NSMutableArray *numDataMarr;//物料数据记录
@property (nonatomic,copy) NSString *isShowPrice;//是否需要显示价格
@end

@implementation MaterialViewController
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    if (textField == self.srBgVTF && self.isTffff) {
        textField.text = @"";
        self.isTffff = NO;
    }
    if (textField == self.srBgVTF) {
        if ([string isEqualToString:@"."]) {
            if (textField.text.length == 0 || [textField.text containsString:@"."]) {
                return NO;
            }
        }
    }
    return YES;
}
- (void)textFieldDidBeginEditing:(UITextField *)textField{
    [self.srBgVTF performSelector:@selector(selectAll:) withObject:nil afterDelay:.0f];
}
-(UIView *)mbV{
    if (!_mbV) {
        _mbV = [[UIView alloc]initWithFrame:self.view.bounds];
        _mbV.backgroundColor = [UIColor colorWithWhite:0 alpha:0.5];
        [self.view.window addSubview:_mbV];
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(mbVAction:)];
        [_mbV addGestureRecognizer:tap];
    }
    return _mbV;
}
-(void)mbVAction:(UITapGestureRecognizer *)tap{
//    self.mbV.hidden = YES;
//    self.srBgV.hidden = YES;
    [self.view endEditing:YES];
}
-(UIView *)srBgV{
    if (!_srBgV) {
        _srBgV = [[UIView alloc]initWithFrame:CGRectMake(50, 0, SCREENWIDTH-100, 200)];
        _srBgV.center = CGPointMake(SCREENWIDTH/2, SCREENHEIGHT/2);
        _srBgV.backgroundColor = [UIColor whiteColor];
        _srBgV.layer.cornerRadius = 5;
        _srBgV.clipsToBounds = YES;
        [self.view.window addSubview:_srBgV];
        UILabel *titleL = [[UILabel alloc]initWithFrame:CGRectMake(0, 25, _srBgV.frame.size.width, 50)];
        titleL.text = @"请输入数量";
        titleL.font = [UIFont systemFontOfSize:20];
        titleL.textAlignment = NSTextAlignmentCenter;
        [_srBgV addSubview:titleL];
        self.wlL = titleL;
        UILabel *slL = [[UILabel alloc]initWithFrame:CGRectMake(10, CGRectGetMaxY(titleL.frame), 0, 50)];
        slL.text = @"数量";
        [_srBgV addSubview:slL];
        UITextField *tf = [[UITextField alloc]initWithFrame:CGRectMake(CGRectGetMaxX(slL.frame), CGRectGetMaxY(titleL.frame), _srBgV.frame.size.width-10-CGRectGetMaxX(slL.frame), 50)];
        tf.delegate = self;
        tf.keyboardType = UIKeyboardTypeDecimalPad;
        tf.layer.borderWidth = 1;
        tf.layer.borderColor = [UIColor lightGrayColor].CGColor;
        tf.layer.cornerRadius = 5;
        tf.clipsToBounds = YES;
        tf.placeholder = @"请输入数量";
        UIView *lV = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 10, 50)];
        tf.leftView = lV;
        tf.leftViewMode = UITextFieldViewModeAlways;
        [_srBgV addSubview:tf];
        self.srBgVTF = tf;
        UIButton *cancleBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        cancleBtn.frame = CGRectMake(10, CGRectGetMaxY(tf.frame)+15, _srBgV.frame.size.width/2-20, 40);
        cancleBtn.layer.cornerRadius = 5;
        cancleBtn.clipsToBounds = YES;
        [cancleBtn setTitle:@"取消" forState:UIControlStateNormal];
        [cancleBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        cancleBtn.backgroundColor = RGBCOLOR(108, 185, 251);
        [_srBgV addSubview:cancleBtn];
        [cancleBtn addTarget:self action:@selector(cancleBtnAction:) forControlEvents:UIControlEventTouchUpInside];
        
        UIButton *quedingBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        quedingBtn.frame = CGRectMake(CGRectGetMaxX(cancleBtn.frame)+20, CGRectGetMaxY(tf.frame)+15, _srBgV.frame.size.width/2-20, 40);
        quedingBtn.layer.cornerRadius = 5;
        quedingBtn.clipsToBounds = YES;
        [quedingBtn setTitle:@"确定" forState:UIControlStateNormal];
        [quedingBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        quedingBtn.backgroundColor = RGBCOLOR(108, 185, 251);
        [_srBgV addSubview:quedingBtn];
        [quedingBtn addTarget:self action:@selector(quedingBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _srBgV;
}
-(void)cancleBtnAction:(UIButton *)btn{
    self.mbV.hidden = YES;
    self.srBgV.hidden = YES;
    self.srBgVTF.text = @"";
    [self.view.window endEditing:YES];
    
    if (self.numDataMarr.count == 0) {
        self.lsddBtn.enabled = NO;
        self.hkBtn.enabled = NO;
        self.lsddBtn.backgroundColor = RGBCOLOR(150, 150, 150);
    }else{
        self.lsddBtn.backgroundColor = RGBCOLOR(108, 185, 251);
        self.lsddBtn.enabled = YES;
        self.hkBtn.enabled = YES;
    }
    
}
-(void)quedingBtnAction:(UIButton *)btn{
    [self.view.window endEditing:YES];
    if (self.srBgVTF.text.length <= 0) {
        self.srBgVTF.text = @"";
        self.mbV.hidden = YES;
        self.srBgV.hidden = YES;
        return;
    }
    if ([self.srBgVTF.text hasSuffix:@"."]) {
        self.srBgVTF.text = [[self.srBgVTF.text componentsSeparatedByString:@"."] firstObject];
    }
    
    
    NSDictionary *d = self.wlLCell.dataDic;
    NSDictionary *dd = self.ckHouse;
    NSString *IsUseAuxiliaryUnit = [NSString stringWithFormat:@"%@",self.ckHouse[@"IsUseAuxiliaryUnit"]];
    int bl = [[[[NSString stringWithFormat:@"%@",d[@"ConvertUnit"]] componentsSeparatedByString:@":"] firstObject] floatValue];
    if ([IsUseAuxiliaryUnit isEqualToString:@"1"]) {
//        int ttt = [self.srBgVTF.text intValue]/bl;
        if ([self.srBgVTF.text intValue]%bl == 0) {
            self.wlLCell.numL.text = [self.srBgVTF.text isEqualToString:@"0"]?@"":self.srBgVTF.text;
        }else{
            NSString *finS = [NSString stringWithFormat:@"%d",([self.srBgVTF.text intValue]/bl + 1)*bl];
            self.wlLCell.numL.text = [self.srBgVTF.text isEqualToString:@"0"]?@"":finS;
            [SVProgressHUD setDefaultStyle:SVProgressHUDStyleDark];
            [SVProgressHUD setMinimumDismissTimeInterval:0.2f];
            [SVProgressHUD showImage:[UIImage imageNamed:@""] status:[NSString stringWithFormat:@"%@的数量必须是%d的倍数",self.wlLCell.dataDic[@"MaterialName"],bl]];
            self.srBgVTF.text = [self.srBgVTF.text isEqualToString:@"0"]?@"":finS;
        }
    }else{
        self.wlLCell.numL.text = [self.srBgVTF.text isEqualToString:@"0"]?@"":self.srBgVTF.text;
    }
    for (int i=0; i<self.numDataMarr.count; i++) {
        if ([[NSString stringWithFormat:@"%@",self.wlLCell.dataDic[@"MaterialID"]] isEqualToString:[NSString stringWithFormat:@"%@",self.numDataMarr[i][@"MaterialID"]]]) {
            NSDictionary *ddd = self.numDataMarr[i];
            [ddd setValue:self.srBgVTF.text forKey:@"MaterialNum"];
            if ([self.srBgVTF.text isEqualToString:@"0"]) {
                [self.numDataMarr removeObject:self.numDataMarr[i]];
                self.wljbL.text = [NSString stringWithFormat:@"%ld",self.numDataMarr.count];
                self.nxljzwlL.text = [NSString stringWithFormat:@"已选中%ld种物料",self.numDataMarr.count];
                self.wljbL.hidden = NO;
                self.nxljzwlL.hidden = NO;
                if (self.numDataMarr.count == 0) {
                    self.wljbL.hidden = YES;
                    self.nxljzwlL.hidden = YES;
                }
            }
            break;
        }
        if (i==self.numDataMarr.count-1 && ![self.srBgVTF.text isEqualToString:@"0"]) {
            NSDictionary *ddd = [self.wlLCell.dataDic mutableCopy];
            [ddd setValue:self.srBgVTF.text forKey:@"MaterialNum"];
            [self.numDataMarr addObject:ddd];
            self.wljbL.text = [NSString stringWithFormat:@"%ld",self.numDataMarr.count];
            self.nxljzwlL.text = [NSString stringWithFormat:@"已选中%ld种物料",self.numDataMarr.count];
            self.wljbL.hidden = NO;
            self.nxljzwlL.hidden = NO;
            if (self.numDataMarr.count == 0) {
                self.wljbL.hidden = YES;
                self.nxljzwlL.hidden = YES;
            }
        }
    }
    if (self.numDataMarr.count == 0 && ![self.srBgVTF.text isEqualToString:@"0"]) {
        NSDictionary *ddd = [self.wlLCell.dataDic mutableCopy];
        [ddd setValue:self.srBgVTF.text forKey:@"MaterialNum"];
        [self.numDataMarr addObject:ddd];
        self.wljbL.text = [NSString stringWithFormat:@"%ld",self.numDataMarr.count];
        self.nxljzwlL.text = [NSString stringWithFormat:@"已选中%ld种物料",self.numDataMarr.count];
        self.wljbL.hidden = NO;
        self.nxljzwlL.hidden = NO;
        if (self.numDataMarr.count == 0) {
            self.wljbL.hidden = YES;
            self.nxljzwlL.hidden = YES;
        }
    }
    if ([self.srBgVTF.text isEqualToString:@"0"]) {
        self.wlLCell.jianBtn.hidden = YES;
        self.wlLCell.pluseBtn.selected = NO;
    }else{
        self.wlLCell.jianBtn.hidden = NO;
        self.wlLCell.jianBtn.selected = YES;
        self.wlLCell.pluseBtn.selected = YES;
    }
    
    
    
    self.srBgVTF.text = @"";
    self.mbV.hidden = YES;
    self.srBgV.hidden = YES;
    
    [self.rightTableView reloadData];
    
    if (self.numDataMarr.count == 0) {
        self.lsddBtn.enabled = NO;
        self.hkBtn.enabled = NO;
        self.lsddBtn.backgroundColor = RGBCOLOR(150, 150, 150);
    }else{
        self.lsddBtn.backgroundColor = RGBCOLOR(108, 185, 251);
        self.lsddBtn.enabled = YES;
        self.hkBtn.enabled = YES;
    }
    [self creatPlist];
}
-(NSMutableArray *)numDataMarr{
    if (!_numDataMarr) {
        _numDataMarr = [[NSMutableArray alloc]init];
    }
    return _numDataMarr;
}
-(NSDictionary *)dataDic{
    if (!_dataDic) {
        _dataDic = [[NSDictionary alloc]init];
    }
    return _dataDic;
}
-(NSMutableArray *)dataMarr{
    if (!_dataMarr) {
        _dataMarr = [[NSMutableArray alloc]init];
    }
    return _dataMarr;
}
-(UITableView *)rightTableView{
    if (!_rightTableView) {
        _rightTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(self.wlssBtn.frame)+5, 100, CGRectGetMinY(self.bottomBGV.frame)-CGRectGetMaxY(self.wlssBtn.frame)-10) style:UITableViewStylePlain];
        _rightTableView.dataSource = self;
        _rightTableView.delegate = self;
//        _myTableView.backgroundColor = [UIColor blueColor];
        [self.view addSubview:_rightTableView];
    }
    return _rightTableView;
}
-(UITableView *)myTableView{
    if (!_myTableView) {
        _myTableView = [[UITableView alloc]initWithFrame:CGRectMake(100, CGRectGetMaxY(self.wlssBtn.frame)+5, SCREENWIDTH-100, CGRectGetMinY(self.bottomBGV.frame)-CGRectGetMaxY(self.wlssBtn.frame)-10) style:UITableViewStylePlain];
        _myTableView.dataSource = self;
        _myTableView.delegate = self;
//        _myTableView.backgroundColor = [UIColor blueColor];
        [self.view addSubview:_myTableView];
    }
    return _myTableView;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    
    [self getData];
    
    [self numDataMarr];
    
    UIButton *wlssBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    wlssBtn.frame = CGRectMake(5, kNavBarAndStatusBarHeight+5, SCREENWIDTH-10, 50);
    wlssBtn.layer.cornerRadius = 5;
    wlssBtn.clipsToBounds = YES;
    wlssBtn.layer.borderWidth = 1;
    wlssBtn.layer.borderColor = RGBCOLOR(200, 200, 200).CGColor;
    [wlssBtn setTitle:@"物料搜索" forState:UIControlStateNormal];
    [wlssBtn setImage:[UIImage imageNamed:@"fangdajing.png"] forState:UIControlStateNormal];
    wlssBtn.imageEdgeInsets = UIEdgeInsetsMake(10,0, 10, 20);
    wlssBtn.imageView.contentMode = UIViewContentModeScaleAspectFit;
    wlssBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    [wlssBtn setTitleColor:RGBCOLOR(190, 190, 190) forState:UIControlStateNormal];
    [self.view addSubview:wlssBtn];
    self.wlssBtn = wlssBtn;
    [wlssBtn addTarget:self action:@selector(wlssBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    
    UIView *leftV = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 40, 40)];
    UIButton *gwcBtnl = [UIButton buttonWithType:UIButtonTypeCustom];
    gwcBtnl.frame = CGRectMake(0, 5, 30, 30);
    gwcBtnl.userInteractionEnabled = NO;
    [gwcBtnl setImage:[UIImage imageNamed:@"货框_03.png"] forState:UIControlStateNormal];
    gwcBtnl.imageView.contentMode = UIViewContentModeScaleAspectFit;
    UITapGestureRecognizer *t = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(leftAction:)];
    [leftV addGestureRecognizer:t];
//    [gwcBtnl addTarget:self action:@selector(leftAction:) forControlEvents:UIControlEventTouchUpInside];
    [leftV addSubview:gwcBtnl];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:leftV];
    
    UIView *bottomBGV = [[UIView alloc]initWithFrame:CGRectMake(0, SCREENHEIGHT-kTabBarHeight-20, SCREENWIDTH, kTabBarHeight+20)];
    bottomBGV.backgroundColor = RGBCOLOR(234, 234, 234);
    [self.view addSubview:bottomBGV];
    
    UIButton *hkBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    hkBtn.frame = CGRectMake(10, 15, 40, 40);
    [hkBtn setImage:[UIImage imageNamed:@"五一路凉菜库_10.png"] forState:UIControlStateNormal];
    hkBtn.imageView.contentMode = UIViewContentModeScaleAspectFit;
    hkBtn.enabled = self.numDataMarr.count == 0?NO:YES;
    self.hkBtn = hkBtn;
    [bottomBGV addSubview:hkBtn];
    [hkBtn addTarget:self action:@selector(ckhkBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    UILabel *wljbL = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 20, 20)];
    wljbL.center = CGPointMake(hkBtn.frame.size.width-5, 5);
    wljbL.layer.cornerRadius = 10;
    wljbL.clipsToBounds = YES;
    wljbL.textAlignment = NSTextAlignmentCenter;
    wljbL.font = [UIFont systemFontOfSize:10];
    wljbL.textColor = [UIColor whiteColor];
    wljbL.backgroundColor = RGBCOLOR(251, 62, 31);
    wljbL.text = self.numDataMarr.count == 0?@"0":[NSString stringWithFormat:@"%ld",self.numDataMarr.count];
    wljbL.hidden = self.numDataMarr.count == 0?YES:NO;
    [hkBtn addSubview:wljbL];
    self.wljbL = wljbL;
    
    UILabel *nxljzwlL = [[UILabel alloc]initWithFrame:CGRectMake(CGRectGetMaxX(hkBtn.frame)+5, 15, 0, 40)];
    nxljzwlL.font = [UIFont systemFontOfSize:15];
    nxljzwlL.text = @"已选中0种物料";
    [bottomBGV addSubview:nxljzwlL];
    self.nxljzwlL = nxljzwlL;
    
    UIButton *lsddBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    lsddBtn.frame = CGRectMake(CGRectGetMaxX(hkBtn.frame)+10, 15, bottomBGV.frame.size.width-CGRectGetMaxX(hkBtn.frame)-20, 40);
    lsddBtn.layer.cornerRadius = 5;
    [lsddBtn setTitle:@"查看货筐" forState:UIControlStateNormal];
    [lsddBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
//    lsddBtn.backgroundColor = RGBCOLOR(108, 185, 251);
    lsddBtn.backgroundColor = self.numDataMarr.count == 0?RGBCOLOR(150, 150, 150):RGBCOLOR(108, 185, 251);
    lsddBtn.enabled = self.numDataMarr.count == 0?NO:YES;
    [bottomBGV addSubview:lsddBtn];
    [lsddBtn addTarget:self action:@selector(ckhkBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    self.bottomBGV = bottomBGV;
    self.lsddBtn = lsddBtn;
    
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeActionL:) name:@"changeee" object:nil];
    
//    self.mbV.hidden = YES;
//    self.srBgV.hidden = YES;
    
    self.rightWlLCellIndexPath = [NSIndexPath indexPathForRow:0 inSection:0];
    
}
-(void)leftAction:(UITapGestureRecognizer *)item{
    self.alerV = [[UIAlertView alloc]initWithTitle:self.title message:@"确定要停止订货吗？" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
    [self.alerV show];
}
-(void)changeActionL:(NSNotification *)not{
    self.wljbL.text = [NSString stringWithFormat:@"%ld",self.numDataMarr.count];
    self.nxljzwlL.text = [NSString stringWithFormat:@"已选中%ld种物料",self.numDataMarr.count];
    if (self.numDataMarr.count == 0) {
        self.wljbL.hidden = YES;
    }else{
        self.wljbL.hidden = NO;
    }
    [self.rightTableView reloadData];
    [self.myTableView reloadData];
    if (self.numDataMarr.count == 0) {
        self.lsddBtn.enabled = NO;
        self.hkBtn.enabled = NO;
        self.lsddBtn.backgroundColor = RGBCOLOR(150, 150, 150);
    }else{
        self.lsddBtn.backgroundColor = RGBCOLOR(108, 185, 251);
        self.lsddBtn.enabled = YES;
        self.hkBtn.enabled = YES;
    }
}
-(void)getData{
    [SVProgressHUD showWithStatus:@"加载中" maskType:SVProgressHUDMaskTypeBlack];
    NSString *str = [[NSUserDefaults standardUserDefaults] objectForKey:@"ipaddress"];
    if (str.length == 0) {
        // 请求头
//        NSString *accessPath = @"http://192.168.0.19:80/Api/OrderGoods/GetMaterialInf";
        NSString *accessPath = @"http://crm.zhenyea.com/Api/OrderGoods/GetMaterialInf";
        NSDictionary *params = [[NSDictionary alloc]init];
        if ([[self.userData allKeys] containsObject:@"IsShowPrice"]) {
            
            // 请求参数字典
            params = @{
                @"strOrganizationNo":[NSString stringWithFormat:@"%@",self.userData[@"OrganizationNo"]],
                @"strUserId":[NSString stringWithFormat:@"%@",self.userData[@"UserID"]],
                @"IsShowPrice":self.userData[@"IsShowPrice"],
                @"strPassword":[NSString stringWithFormat:@"%@",self.userData[@"UserPass"]],
                @"strIMEI":[FCUUID uuidForVendor]
            };
        }else{
            // 请求参数字典
            params = @{
                @"strOrganizationNo":[NSString stringWithFormat:@"%@",self.userData[@"OrganizationNo"]],
                @"strUserId":[NSString stringWithFormat:@"%@",self.userData[@"UserID"]],
                @"strPassword":[NSString stringWithFormat:@"%@",self.userData[@"UserPass"]],
                @"strIMEI":[FCUUID uuidForVendor]
            };
        }
        
        //创建配置信息
        NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
        //设置请求超时时间：5秒
        configuration.timeoutIntervalForRequest = 5;
        //创建会话
        NSURLSession *session = [NSURLSession sessionWithConfiguration: configuration delegate: nil delegateQueue: [NSOperationQueue mainQueue]];
        NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@",accessPath]]];
        //设置请求方式：POST
        [request setHTTPMethod:@"POST"];
        [request setValue:@"application/json" forHTTPHeaderField:@"content-Type"];
        [request setValue:@"application/json;charset=gb2312" forHTTPHeaderField:@"Accept"];
        
        //data的字典形式转化为data
        NSData *jsonData = [NSJSONSerialization dataWithJSONObject:params options:NSJSONWritingPrettyPrinted error:nil];
        //设置请求体
        [request setHTTPBody:jsonData];
        
        NSURLSessionDataTask * dataTask =[session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
            [SVProgressHUD dismiss];
            if (error == nil) {
                NSStringEncoding encoding = CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000);
                NSString *receiveStr = [[NSString alloc]initWithData:data encoding:encoding];
                NSData * aData = [receiveStr dataUsingEncoding:NSUTF8StringEncoding];
                NSError *errorr = nil;
                id response = [NSJSONSerialization JSONObjectWithData:aData options:NSJSONReadingMutableContainers error:&errorr];
                if ([response isKindOfClass:[NSDictionary class]]) {
                    // 请求成功数据处理
                    NSString *IsResult = [NSString stringWithFormat:@"%@",[response objectForKey:@"IsResult"]];
                    if ([IsResult isEqualToString:@"1"]) {
                        self.dataMarr = [response[@"Data"] mutableCopy];
                        if (self.neeeNumDataMarr.count!=0) {
                            for (int i=0; i<self.dataMarr.count; i++) {
                                NSArray *aaaaa = self.dataMarr[i][@"MaterialInfs"];
                                for (int j=0; j<aaaaa.count; j++) {
                                    for (int z=0; z<self.neeeNumDataMarr.count; z++) {
                                        if ([[NSString stringWithFormat:@"%@",self.neeeNumDataMarr[z][@"MaterialID"]] isEqualToString:[NSString stringWithFormat:@"%@",aaaaa[j][@"MaterialID"]]]) {
                                            [self.numDataMarr addObject:self.neeeNumDataMarr[z]];
                                        }
                                    }
                                }
                            }
                        }
                        self.wljbL.text = self.numDataMarr.count == 0?@"0":[NSString stringWithFormat:@"%ld",self.numDataMarr.count];
                        self.wljbL.hidden = self.numDataMarr.count == 0?YES:NO;
                        self.hkBtn.enabled = self.numDataMarr.count == 0?NO:YES;
                        self.lsddBtn.backgroundColor = self.numDataMarr.count == 0?RGBCOLOR(150, 150, 150):RGBCOLOR(108, 185, 251);
                        self.lsddBtn.enabled = self.numDataMarr.count == 0?NO:YES;
                        [self.myTableView reloadData];
                    }else{
                        [SVProgressHUD setDefaultStyle:SVProgressHUDStyleDark];
                        [SVProgressHUD setMinimumDismissTimeInterval:0.2f];
                        [SVProgressHUD showImage:[UIImage imageNamed:@""] status:[NSString stringWithFormat:@"%@",response[@"Message"]]];
                    }
                } else {
                    NSData * data = error.userInfo[@"com.alamofire.serialization.response.error.data"];
                    NSString * str = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
                    NSLog(@"服务器的错误原因:%@",str);
                    [SVProgressHUD dismiss];
                }
            }else{
                NSData * data = error.userInfo[@"com.alamofire.serialization.response.error.data"];
                NSString * str = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
                NSLog(@"服务器的错误原因:%@",str);
                [SVProgressHUD dismiss];
            }
        }];
        [dataTask resume];

//        AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
//
//        NSMutableURLRequest *request = [[AFJSONRequestSerializer serializer] requestWithMethod:@"POST" URLString:accessPath parameters:params error:nil];
//        request.timeoutInterval = 10.f;
//        [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
//        [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
//
//        NSURLSessionDataTask *task = [manager dataTaskWithRequest:request completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
//            [SVProgressHUD dismiss];
//            if (!error) {
//                if ([responseObject isKindOfClass:[NSDictionary class]]) {
//                    // 请求成功数据处理
//                    NSString *IsResult = [NSString stringWithFormat:@"%@",[responseObject objectForKey:@"IsResult"]];
//                    if ([IsResult isEqualToString:@"1"]) {
//                        self.dataMarr = [responseObject[@"Data"] mutableCopy];
//                        if (self.neeeNumDataMarr.count!=0) {
//                            for (int i=0; i<self.dataMarr.count; i++) {
//                                NSArray *aaaaa = self.dataMarr[i][@"MaterialInfs"];
//                                for (int j=0; j<aaaaa.count; j++) {
//                                    for (int z=0; z<self.neeeNumDataMarr.count; z++) {
//                                        if ([[NSString stringWithFormat:@"%@",self.neeeNumDataMarr[z][@"MaterialID"]] isEqualToString:[NSString stringWithFormat:@"%@",aaaaa[j][@"MaterialID"]]]) {
//                                            [self.numDataMarr addObject:self.neeeNumDataMarr[z]];
//                                        }
//                                    }
//                                }
//                            }
//                        }
//                        self.wljbL.text = self.numDataMarr.count == 0?@"0":[NSString stringWithFormat:@"%ld",self.numDataMarr.count];
//                        self.wljbL.hidden = self.numDataMarr.count == 0?YES:NO;
//                        self.hkBtn.enabled = self.numDataMarr.count == 0?NO:YES;
//                        self.lsddBtn.backgroundColor = self.numDataMarr.count == 0?RGBCOLOR(150, 150, 150):RGBCOLOR(108, 185, 251);
//                        self.lsddBtn.enabled = self.numDataMarr.count == 0?NO:YES;
//                        [self.myTableView reloadData];
//                    }else{
//                        [SVProgressHUD setMinimumDismissTimeInterval:0.2f];
//                        [SVProgressHUD showImage:[UIImage imageNamed:@""] status:[NSString stringWithFormat:@"%@",responseObject[@"Message"]]];
//                    }
//                } else {
//                    
//                }
//            } else {
//                NSLog(@"请求失败error=%@", error);
//            }
//        }];
//
//        [task resume];
    }else{
        [NetTools postWithUrl:[NSString stringWithFormat:@"http://%@/ldcy/OrderGoods/OrderGoods.asmx/GetMaterialInf",str] pararms:@{} success:^(id  _Nonnull json) {
            [SVProgressHUD dismiss];
            if ([[NSString stringWithFormat:@"%@",json[@"IsResult"]] isEqualToString:@"1"]) {
                self.dataMarr = [json[@"Data"] mutableCopy];
                if (self.neeeNumDataMarr.count!=0) {
                    for (int i=0; i<self.dataMarr.count; i++) {
                        NSArray *aaaaa = self.dataMarr[i][@"MaterialInfs"];
                        for (int j=0; j<aaaaa.count; j++) {
                            for (int z=0; z<self.neeeNumDataMarr.count; z++) {
                                if ([[NSString stringWithFormat:@"%@",self.neeeNumDataMarr[z][@"MaterialID"]] isEqualToString:[NSString stringWithFormat:@"%@",aaaaa[j][@"MaterialID"]]]) {
                                    [self.numDataMarr addObject:self.neeeNumDataMarr[z]];
                                }
                            }
                        }
                    }
                }
                self.wljbL.text = self.numDataMarr.count == 0?@"0":[NSString stringWithFormat:@"%ld",self.numDataMarr.count];
                self.wljbL.hidden = self.numDataMarr.count == 0?YES:NO;
                self.hkBtn.enabled = self.numDataMarr.count == 0?NO:YES;
                self.lsddBtn.backgroundColor = self.numDataMarr.count == 0?RGBCOLOR(150, 150, 150):RGBCOLOR(108, 185, 251);
                self.lsddBtn.enabled = self.numDataMarr.count == 0?NO:YES;
                [self.myTableView reloadData];
            }else{
                [SVProgressHUD setMinimumDismissTimeInterval:0.2f];
                [SVProgressHUD showImage:[UIImage imageNamed:@""] status:[NSString stringWithFormat:@"%@",json[@"Message"]]];
            }
        } fail:^(NSError * _Nonnull error) {
            [SVProgressHUD dismiss];
        }];
    }
    
}
-(void)wlssBtnAction:(UIButton *)btn{
    //物料搜索
    TheMaterialSearchViewController *tmsVC = [[TheMaterialSearchViewController alloc]init];
    tmsVC.dataArr = self.dataMarr;
    tmsVC.yjDataArr = self.numDataMarr;
    tmsVC.userDic = self.userData;
    tmsVC.houseDic = self.ckHouse;
    [self.navigationController pushViewController:tmsVC animated:YES];
}
-(void)ckhkBtnAction:(UIButton *)btn{
    if (self.numDataMarr.count == 0) {
        [SVProgressHUD setDefaultStyle:SVProgressHUDStyleDark];
        [SVProgressHUD setMinimumDismissTimeInterval:0.2f];
        [SVProgressHUD showImage:[UIImage imageNamed:@""] status:@"您还没有添加物料！"];
    }else{
        //查看货框
        CargoBoxViewController *cbVC = [[CargoBoxViewController alloc]init];
        cbVC.dataMarr = self.numDataMarr;
        cbVC.houseDic = self.ckHouse;
        cbVC.userDic = self.userData;
        [self.navigationController pushViewController:cbVC animated:YES];
    }
}
#pragma mark <UITableViewDelegate,UITableViewDataSource>
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (tableView == self.myTableView) {
        NSDictionary *dd = self.dataMarr[section];
        NSArray *arr = dd[@"MaterialInfs"];
        return arr.count;
    }else{
        return self.dataMarr.count;
    }
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    if (tableView == self.myTableView) {
        return self.dataMarr.count;
    }else{
        return 1;
    }
}
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (alertView == self.alerV) {
        if (buttonIndex == 1) {
            [self delectPlist];
            [[NSUserDefaults standardUserDefaults] setObject:@"" forKey:@"remarkeeee"];
            [[NSUserDefaults standardUserDefaults] synchronize];
            [self.navigationController popViewControllerAnimated:YES];
        }
    }else{
        if (buttonIndex == 1) {
                
                for (int i=0; i<self.numDataMarr.count; i++) {
                    if ([[NSString stringWithFormat:@"%@",self.wlLCell.dataDic[@"MaterialID"]] isEqualToString:[NSString stringWithFormat:@"%@",self.numDataMarr[i][@"MaterialID"]]]) {
                        NSDictionary *ddd = self.numDataMarr[i];
                        [ddd setValue:@"" forKey:@"MaterialNum"];
                        [self.numDataMarr removeObject:self.numDataMarr[i]];
                        self.srBgVTF.text = @"";

                        self.wljbL.text = [NSString stringWithFormat:@"%ld",self.numDataMarr.count];
        //                self.cell.nxljzwlL.text = [NSString stringWithFormat:@"已选中%ld种物料",self.numDataMarr.count];
                        
                        self.wljbL.hidden = NO;
                        self.nxljzwlL.hidden = NO;
                        if (self.numDataMarr.count == 0) {
                            self.wljbL.hidden = YES;
                            self.nxljzwlL.hidden = YES;
                        }
                        break;
                    }
                    if (i==self.numDataMarr.count-1) {
                        NSDictionary *ddd = self.wlLCell.dataDic;
                        [ddd setValue:@"" forKey:@"MaterialNum"];
                        [self.numDataMarr addObject:ddd];
                        self.wljbL.text = [NSString stringWithFormat:@"%ld",self.numDataMarr.count];
                        self.nxljzwlL.text = [NSString stringWithFormat:@"已选中%ld种物料",self.numDataMarr.count];
                        self.wljbL.hidden = NO;
                        self.nxljzwlL.hidden = NO;
                        if (self.numDataMarr.count == 0) {
                            self.wljbL.hidden = YES;
                            self.nxljzwlL.hidden = YES;
                        }
                    }
                }
                self.wlLCell.numL.text = @"";
                self.wlLCell.jianBtn.selected = NO;
                self.wlLCell.pluseBtn.selected = NO;
                self.wlLCell.jianBtn.hidden = YES;
                [self.rightTableView reloadData];
            if (self.numDataMarr.count == 0) {
                self.lsddBtn.enabled = NO;
                self.hkBtn.enabled = NO;
                self.lsddBtn.backgroundColor = RGBCOLOR(150, 150, 150);
            }else{
                self.lsddBtn.backgroundColor = RGBCOLOR(108, 185, 251);
                self.lsddBtn.enabled = YES;
                self.hkBtn.enabled = YES;
            }
            }
    }
    
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (tableView == self.rightTableView) {
        static NSString *idf = @"RightMaterialTableViewCell";
        RightMaterialTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:idf];
        if (!cell) {
            cell = [[RightMaterialTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:idf];
        }
        cell.nameL.text = [NSString stringWithFormat:@"%@",self.dataMarr[indexPath.row][@"CategoryName"]];
//        if (indexPath.row == 0 &&
//            !self.rightWlLCell) {
//            cell.nameL.backgroundColor = [UIColor whiteColor];
//            self.rightWlLCell = cell;
//        }else{
            if (self.rightWlLCellIndexPath == indexPath) {
                cell.nameL.backgroundColor = [UIColor whiteColor];
                self.rightWlLCell = cell;
            }else{
                cell.nameL.backgroundColor = RGBCOLOR(209, 209, 209);
            }
//        }
        cell.ccciiiddd = [NSString stringWithFormat:@"%@",self.dataMarr[indexPath.row][@"MaterialCategoryId"]];
        
        //类目角标
        int nnnnn = 0;
        for (int i=0; i<self.dataMarr.count; i++) {
            for (int j=0; j<self.numDataMarr.count; j++) {
                if ([[NSString stringWithFormat:@"%@",self.dataMarr[i][@"MaterialCategoryId"]] isEqualToString:[NSString stringWithFormat:@"%@",self.numDataMarr[j][@"MaterialCategoryId"]]] && [[NSString stringWithFormat:@"%@",self.numDataMarr[j][@"MaterialCategoryId"]] isEqualToString:cell.ccciiiddd]) {
                    nnnnn++;
                }
            }
        }
        if (nnnnn == 0) {
            cell.numL.hidden = YES;
        }else{
            cell.numL.hidden = NO;
            cell.numL.text = [NSString stringWithFormat:@"%d",nnnnn];
        }
        return cell;
    }else{
        static NSString *idf = @"LeftMaterialTableViewCell";
        LeftMaterialTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:idf];
        if (!cell) {
            cell = [[LeftMaterialTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:idf];
        }
        NSArray *aaa = self.dataMarr[indexPath.section][@"MaterialInfs"];
        cell.dataDic = aaa[indexPath.row];
        for (int i=0; i<self.numDataMarr.count; i++) {
            if ([[NSString stringWithFormat:@"%@",cell.dataDic[@"MaterialID"]] isEqualToString:[NSString stringWithFormat:@"%@",self.numDataMarr[i][@"MaterialID"]]]) {
                cell.numL.text = [[NSString stringWithFormat:@"%@",self.numDataMarr[i][@"MaterialNum"]] isEqualToString:@"0"]?@"":[NSString stringWithFormat:@"%@",self.numDataMarr[i][@"MaterialNum"]];
                cell.pluseBtn.selected = YES;
                cell.jianBtn.hidden = NO;
                cell.jianBtn.selected = YES;
                break;
            }
            if (i==self.numDataMarr.count-1) {
                cell.numL.text = @"";
                cell.pluseBtn.selected = NO;
                cell.jianBtn.hidden = YES;
            }
        }
        if (self.numDataMarr.count == 0) {
            cell.numL.text = @"";
            cell.pluseBtn.selected = NO;
            cell.jianBtn.hidden = YES;
        }
        __weak typeof(self) weakSelf = self;
        __weak typeof(cell) weakCell = cell;
        cell.jianBlock = ^(NSString *num) {//消除
            weakSelf.wlLCell = weakCell;
            weakSelf.wlLCellIndexPath = indexPath;
            UIAlertView *a = [[UIAlertView alloc] initWithTitle:[NSString stringWithFormat:@"%@",weakCell.dataDic[@"MaterialName"]] message:@"确定要删除么？" delegate:nil cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
            a.delegate = self;
            [a show];
        };
        cell.pluseBlock = ^(NSString *num) {

            weakSelf.isTffff = YES;
            weakSelf.mbV.hidden = NO;
            weakSelf.srBgV.hidden = NO;
            weakSelf.wlLCell = weakCell;
            weakSelf.wlL.text = [NSString stringWithFormat:@"%@",weakCell.dataDic[@"MaterialName"]];
            if (![weakCell.numL.text isEqualToString:@"0"]) {
                weakSelf.srBgVTF.text = weakCell.numL.text;
            }
            

            [weakSelf.srBgVTF becomeFirstResponder];
        };
        return cell;
    }
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (tableView == self.rightTableView) {
        return 50;
    }else{
        return 110;
    }
}
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    if (tableView == self.myTableView) {
        static NSString*ss = @"customUITableViewHeaderFooterView";
        UITableViewHeaderFooterView *l = [[UITableViewHeaderFooterView alloc]initWithReuseIdentifier:ss];
        l.backgroundColor = RGBCOLOR(251, 251, 251);
        l.textLabel.text = [NSString stringWithFormat:@"%@",self.dataMarr[section][@"CategoryName"]];
        return l;
    }else{
        return nil;
    }
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (tableView == self.myTableView) {
        return 30;
    }else{
        return 0;;
    }
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (tableView == self.rightTableView) {
        NSIndexPath *scrollIP = [NSIndexPath indexPathForRow:0 inSection:indexPath.row];
        self.didscroll = YES;
        [self.myTableView scrollToRowAtIndexPath:scrollIP atScrollPosition:UITableViewScrollPositionTop animated:YES];
        self.rightWlLCell.nameL.backgroundColor = self.rightWlLCellIndexPath == indexPath?[UIColor whiteColor]:RGBCOLOR(209, 209, 209);
        RightMaterialTableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
        cell.nameL.backgroundColor = [UIColor whiteColor];
        self.rightWlLCell = cell;
        self.rightWlLCellIndexPath = indexPath;
    }
}
-(void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
    if (scrollView == self.myTableView) {
        self.didscroll = NO;
    }else{
        self.didscroll = YES;
    }
}
-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    if (scrollView == self.myTableView) {
        self.didscroll = YES;
    }
}
-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    if (scrollView == self.myTableView) {
        self.didscroll = NO;
    }else{
        self.didscroll = YES;
    }
//    // 如果是 左侧的 tableView 直接return
//    if (scrollView == self.rightTableView) return;
//
//    // 取出显示在 视图 且最靠上 的 cell 的 indexPath
//    NSIndexPath *topHeaderViewIndexpath = [[self.myTableView indexPathsForVisibleRows] firstObject];
//
//    // 左侧 talbelView 移动到的位置 indexPath
//    NSIndexPath *moveToIndexpath = [NSIndexPath indexPathForRow:topHeaderViewIndexpath.section inSection:0];
//
//
//    RightMaterialTableViewCell *c = [self.rightTableView cellForRowAtIndexPath:moveToIndexpath];
//    if (c == self.rightWlLCell) {
//        return;
//    }
//    self.rightWlLCell.nameL.backgroundColor = RGBCOLOR(209, 209, 209);
//    self.rightWlLCell = c;
//    self.rightWlLCell.nameL.backgroundColor = [UIColor whiteColor];
}
//MARK: - 一个方法就能搞定 右边滑动时跟左边的联动
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {

    // 如果是 左侧的 tableView 直接return
    if (scrollView == self.rightTableView || self.didscroll) return;

    // 取出显示在 视图 且最靠上 的 cell 的 indexPath
    NSIndexPath *topHeaderViewIndexpath = [[self.myTableView indexPathsForVisibleRows] firstObject];

    // 左侧 talbelView 移动到的位置 indexPath
    NSIndexPath *moveToIndexpath = [NSIndexPath indexPathForRow:topHeaderViewIndexpath.section inSection:0];


    RightMaterialTableViewCell *c = [self.rightTableView cellForRowAtIndexPath:moveToIndexpath];
    if (c == self.rightWlLCell) {
        return;
    }
    self.rightWlLCell.nameL.backgroundColor = RGBCOLOR(209, 209, 209);
    self.rightWlLCell = c;
    self.rightWlLCell.nameL.backgroundColor = [UIColor whiteColor];
}
//1.创建plist文件
-(void)creatPlist{
    //1.创建plist文件的路径(plist文件要存储的本地路径)
    NSString *filePath = [NSHomeDirectory() stringByAppendingString:@"/Documents/myPlist.plist"];
    
    NSLog(@"%@",filePath);
   
    //2.准备存储的数据
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
   
    [dic setValue:self.ckHouse forKey:@"ckHouse"]; //仓库选择
   
    [dic setValue:self.userData forKey:@"userData"];//用户数据
   
    [dic setValue:self.numDataMarr forKey:@"numDataMarr"];//已点物料
   
    //3.将准备好的数据存储到plist文件中
    [dic writeToFile:filePath atomically:YES];
}
-(void)delectPlist{
    //清除plist文件，可以根据我上面讲的方式进去本地查看plist文件是否被清除
    NSFileManager *fileMger = [NSFileManager defaultManager];
    NSString *xiaoXiPath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0]stringByAppendingPathComponent:@"myPlist.plist"];
    //如果文件路径存在的话
    BOOL bRet = [fileMger fileExistsAtPath:xiaoXiPath];
    if (bRet) {
        NSError *err;
        [fileMger removeItemAtPath:xiaoXiPath error:&err];
    }
}
@end
